<template>
  <div class="messages-container">
    <!-- 顶部导航栏 -->
    <div class="top-tabs">
      <el-tabs v-model="activeTab" class="custom-tabs" @tab-change="handleTabChange">
        <el-tab-pane label="客服消息" name="chat" />
      </el-tabs>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 聊天界面 -->
      <div v-show="activeTab === 'chat'" class="chat-section">
        <div class="chat-window">
          <div class="chat-header">
            <div class="chat-header-info">
              <span class="current-user-name">餐厅客服</span>
              <span class="user-status">在线</span>
            </div>
          </div>

          <div class="messages" ref="messagesContainer">
            <el-scrollbar view-class="messages-list">
              <el-empty v-if="messages.length === 0" description="暂无消息" />
              <template v-if="messages.length > 0">
                <div class="messages-date-divider">
                  <span>{{ formatDate(new Date()) }}</span>
                </div>
                <div
                  v-for="msg in messages"
                  :key="msg.id"
                  :class="['message-wrapper', msg.sender === 'user' ? 'sent' : 'received']"
                >
                  <div class="message-time">{{ formatMessageTime(msg.time) }}</div>
                  <div class="message">
                    <el-avatar
                      :size="30"
                      :src="msg.sender === 'user' ? userAvatar : adminAvatar"
                    />
                    <div class="message-content">
                      <div class="message-text">{{ msg.content }}</div>
                    </div>
                  </div>
                </div>
              </template>
            </el-scrollbar>
          </div>

          <div class="message-input">
            <div class="input-toolbar">
              <el-tooltip content="发送图片">
                <el-upload
                  action="/api/upload"
                  :show-file-list="false"
                  :on-success="handleImageUpload"
                  accept="image/*"
                >
                  <el-button link>
                    <el-icon><Picture /></el-icon>
                  </el-button>
                </el-upload>
              </el-tooltip>
              <el-tooltip content="发送表情">
                <el-button link @click="showEmojiPicker">
                  <el-icon><ChatRound /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
            <div class="input-area">
              <el-input
                v-model="messageInput"
                type="textarea"
                :rows="3"
                placeholder="输入消息..."
                resize="none"
                @keyup.enter.exact="sendMessage"
                @keyup.ctrl.enter="messageInput += '\n'"
              />
              <el-button type="primary" @click="sendMessage" :disabled="!messageInput.trim()">
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { Check, Picture, CircleCheck, ChatRound } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()
const activeTab = ref('chat')
const messages = ref([])
const messageInput = ref('')
const promotions = ref([])
const isOnline = ref(true)
const userAvatar = ref(store.state.user?.avatar || '/default-avatar.png')
const adminAvatar = ref('/admin-avatar.png')
const isDisabled = ref(true)
const pollingInterval = ref(null)

console.log('Messages component mounted')

// 添加表情功能方法
const showEmojiPicker = () => {
  ElMessage.info('表情功能开发中')
}

// 确保用户信息已加载
const loadUserInfo = async () => {
  try {
    // 先从 store 中获取用户信息
    if (store.state.user && store.state.user.id) {
      console.log('Using user info from store:', store.state.user)
      userAvatar.value = store.state.user.avatar || '/default-avatar.png'
      return
    }

    // 从 localStorage 获取
    const userStr = localStorage.getItem('user')
    console.log('User info from localStorage:', userStr)

    if (!userStr || userStr === 'undefined') {
      console.error('No user info in localStorage')
      router.push('/login')
      return
    }

    try {
      const userData = JSON.parse(userStr)
      if (!userData || !userData.id) {
        console.error('Invalid user data:', userData)
        router.push('/login')
        return
      }

      // 更新 store
      store.commit('setUserInfo', userData)
      userAvatar.value = userData.avatar || '/default-avatar.png'
      console.log('User info loaded from localStorage:', userData)
    } catch (error) {
      console.error('Failed to parse user data:', error)
      router.push('/login')
    }
  } catch (error) {
    console.error('Failed to load user info:', error)
    ElMessage.error('获取用户信息失败，请重新登录')
    router.push('/login')
  }
}

// 修改消息加载逻辑
const loadMessages = async () => {
  try {
    // 确保有用户信息
    if (!store.state.user?.id) {
      await loadUserInfo()
    }

    const { data } = await axios.get('/messages', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    console.log("messages: ", data)
    if (Array.isArray(data.messages)) {
      messages.value = data.messages.map(msg => ({
        id: msg.id,
        content: msg.content,
        time: msg.time,
        sender: msg.sender,
        type: msg.type,
        read: msg.read,
        status: msg.status
      }))
    }
    scrollToBottom()
  } catch (error) {
    console.error('加载消息失败:', error)
    ElMessage.error('加载消息失败')
  }
}

// 处理输入变化
const handleInput = (value) => {
  isDisabled.value = !value || value.trim().length === 0
}

// 处理回车发送
const handleEnterSend = () => {
  if (!isDisabled.value) {
    sendMessage()
  }
}

// 开始轮询
const startPolling = () => {
  pollingInterval.value = setInterval(() => {
    loadMessages()
  }, 2000)
}

// 停止轮询
const stopPolling = () => {
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value)
    pollingInterval.value = null
  }
}

// 修改发送消息逻辑
const sendMessage = async () => {
  const content = messageInput.value.trim()
  if (!content) return
  
  try {
    const { data } = await axios.post('/messages', {
      content: content,
      type: 'text'
    }, {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    messageInput.value = ''
    isDisabled.value = true
    await loadMessages()
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败')
  }
}

// 处理图片上传
const handleImageUpload = async (res) => {
  if (res.url) {
    try {
      await axios.post('/api/messages', {
        content: res.url,
        type: 'image'
      }, {
        headers: {
          'Authorization': `Bearer ${store.state.token}`
        }
      })
      await loadMessages()
    } catch (error) {
      console.error('发送图片失败:', error)
      ElMessage.error('发送图片失败')
    }
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  const container = document.querySelector('.messages .el-scrollbar__wrap')
  if (container) {
    container.scrollTop = container.scrollHeight
  }
}

// 修改时间格式化函数
const formatMessageTime = (time) => {
  if (!time) return ''
  return dayjs(time).format('HH:mm')
}

const formatDate = (date) => {
  if (!date) return ''
  return dayjs(date).format('YYYY年MM月DD日')
}

// 切换标签页时的处理
const handleTabChange = (tab) => {
  if (tab === 'chat') {
    startPolling()
  } else {
    stopPolling()
  }
}

onMounted(async () => {
  console.log('Component mounted, loading data...')
  await loadUserInfo()
  loadMessages()  // 加载历史消息
  startPolling()
})

onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
/* 复用管理员端的样式，但需要调整一些细节 */
.messages-container {
  padding: 20px;
  height: calc(100vh - 120px);
  margin: -20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 顶部导航栏样式 */
.top-tabs {
  background: #fff;
  border-radius: 4px;
  padding: 10px 20px;
  border: 1px solid #dcdfe6;
  margin-bottom: 20px;
}

.main-content {
  flex: 1;
  overflow: hidden;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.chat-section {
  display: flex;
  height: 100%;
  overflow: hidden;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  height: 100%;
  background: #f5f7fa;
}

.chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #dcdfe6;
  background: #fff;
}

.chat-header-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.current-user-name {
  font-size: 16px;
  font-weight: 600;
}

.user-status {
  font-size: 12px;
  color: #909399;
}

.messages {
  flex: 1;
  overflow: hidden;
  background: #f5f7fa;
  padding: 20px;
}

.messages-date-divider {
  text-align: center;
  margin-bottom: 20px;
}

.messages-date-divider span {
  padding: 0 10px;
  background: #fff;
  border-radius: 4px;
  font-size: 12px;
  color: #909399;
}

.message-wrapper {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
}

.message-wrapper.sent {
  align-items: flex-end;
}

.message-wrapper.received {
  align-items: flex-start;
}

.message {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  max-width: 70%;
}

.message-wrapper.sent .message {
  flex-direction: row-reverse;
}

.message-wrapper.received .message {
  flex-direction: row;
}

.message-content {
  margin: 0 10px;
}

.message-text {
  padding: 10px 15px;
  font-size: 14px;
  line-height: 1.5;
  word-break: break-word;
}

.message-wrapper.sent .message-text {
  background-color: #95ec69;
  border-radius: 20px 3px 20px 20px;
  margin-right: 10px;
}

.message-wrapper.received .message-text {
  background-color: #f4f4f5;
  border-radius: 3px 20px 20px 20px;
  margin-left: 10px;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin: 5px 0;
  text-align: center;
}

.messages-list {
  padding: 20px;
  height: 100%;
}

.message-input {
  border-top: 1px solid #dcdfe6;
  background: #fff;
  padding: 10px 20px;
}

.input-toolbar {
  padding: 10px;
  border-bottom: 1px solid #f0f2f5;
  display: flex;
  gap: 10px;
}

.input-area {
  padding: 10px 0;
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.el-button {
  min-width: 80px;
  height: 40px;
}
</style> 